import { useEffect } from 'react'
import useGetUserInfo from '../../components/hooks/useGetUserInfo'
import { useLocation, useNavigate } from 'react-router-dom'
import { HOME_PATHNAME, LOGIN_PATHNAME, MANAGE_INDEX_PATHNAME, REGISTER_PATHNAME } from '../../router'

export default function useNavPage(waitingUserData: boolean) {
  const nav = useNavigate()
  const { pathname } = useLocation()

  const { username } = useGetUserInfo()

  useEffect(() => {
    if (waitingUserData) return

    if (username) {
      if ([LOGIN_PATHNAME, REGISTER_PATHNAME].includes(pathname)) {
        nav({ pathname: MANAGE_INDEX_PATHNAME })
      }
      return
    }

    if ([HOME_PATHNAME, LOGIN_PATHNAME, REGISTER_PATHNAME].includes(pathname)) {
      return
    } else {
      nav({ pathname: LOGIN_PATHNAME })
    }
  }, [waitingUserData, username, pathname])
}
